/**
 * 
 */
package com.fc.push.handler.pub.verify;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import com.fc.push.mqtt.MqttConfig;

/**
 * @author Administrator
 *
 */
public class Main {
	//
	//867840020273125
	
	public static void main(String[] args){
		MqttClient client = null;
		try {
			//向推送服务器注册
			//new PublishServiceRegisterHandlerTest().run();
			
			//连接MQTT
			client = new MqttClient("tcp://112.74.101.75:1883", "909eb899026ee981f0c575a", new MemoryPersistence());
			MqttConnectOptions options = null;;
			if(options  == null){
				options = new MqttConnectOptions();
				options.setCleanSession(true);
				options.setConnectionTimeout(10);
				options.setKeepAliveInterval(20);
				if(MqttConfig.getUsername() != null && !MqttConfig.getUsername().isEmpty()){
					options.setUserName(MqttConfig.getUsername());
					options.setPassword(MqttConfig.getPassword().toCharArray());
				}
			}
			client.connect(options);
			//订阅主题：推送服务器返回的clientid
			client.subscribe("909eb899026ee981f0c575a");
			client.setCallback(new MqttCallback(){

				@Override
				public void connectionLost(Throwable arg0) {
					
				}

				@Override
				public void deliveryComplete(IMqttDeliveryToken arg0) {
					
				}

				@Override
				public void messageArrived(String arg0, MqttMessage arg1) throws Exception {
					System.out.println(arg1.toString());
				}
				
			});
		}catch(Exception e){
			e.printStackTrace();
		}
	
	}
	static class SimpleCallbackHandler implements MqttCallback {
		/* (non-Javadoc)
		 * @see org.eclipse.paho.client.mqttv3.MqttCallback#connectionLost(java.lang.Throwable)
		 */
		@Override
		public void connectionLost(Throwable arg0) {
			// TODO Auto-generated method stub
			arg0.printStackTrace();
			System.out.println(arg0.getMessage());
		}

		/* (non-Javadoc)
		 * @see org.eclipse.paho.client.mqttv3.MqttCallback#deliveryComplete(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken)
		 */
		@Override
		public void deliveryComplete(IMqttDeliveryToken arg0) {
			// TODO Auto-generated method stub
			System.out.println("");
		}

		/* (non-Javadoc)
		 * @see org.eclipse.paho.client.mqttv3.MqttCallback#messageArrived(java.lang.String, org.eclipse.paho.client.mqttv3.MqttMessage)
		 */
		@Override
		public void messageArrived(String arg0, MqttMessage arg1) throws Exception {
			 // TODO Auto-generated method stub
			 System.out.println("消息: " + new String(arg1.getPayload()));
		}

	}
}
